/****************************************************************************
 *
 *   Copyright (c) 2025 H743 Flight Controller Project. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include <px4_platform_common/px4_work_queue/work_queue_manager.hpp>
#include <px4_platform_common/px4_work_queue/work_queue.hpp>
#include "FreeRTOS.h"
#include "task.h"
#include <string.h>

// Forward declaration of debug_printf from main.c
extern "C" int debug_printf(const char *format, ...);

static int test_passed = 0;
static int test_failed = 0;

#define TEST_ASSERT(condition, message) \
	do { \
		if (condition) { \
			test_passed++; \
		} else { \
			test_failed++; \
			debug_printf("  [FAIL] %s\n", message); \
		} \
	} while(0)

/**
 * Test 1: Start and stop manager
 */
static void test_start_stop_manager()
{
	debug_printf("Test 1: Start and stop manager\n");

	int ret = px4::WorkQueueManagerStart();
	TEST_ASSERT(ret == 0, "WorkQueueManagerStart returns 0");

	// Give it time to start
	vTaskDelay(pdMS_TO_TICKS(100));

	// Try to start again (should fail)
	ret = px4::WorkQueueManagerStart();
	TEST_ASSERT(ret != 0, "WorkQueueManagerStart fails when already running");

	// Stop manager (should fail - no active WQs but we haven't created any)
	ret = px4::WorkQueueManagerStop();
	TEST_ASSERT(ret == 0, "WorkQueueManagerStop returns 0");

	// Give it time to stop
	vTaskDelay(pdMS_TO_TICKS(100));
}

/**
 * Test 2: Create work queues
 */
static void test_create_work_queues()
{
	debug_printf("Test 2: Create work queues\n");

	// Start manager
	int ret = px4::WorkQueueManagerStart();
	TEST_ASSERT(ret == 0, "WorkQueueManagerStart returns 0");

	vTaskDelay(pdMS_TO_TICKS(100));

	// Create test work queue 1
	px4::WorkQueue *wq1 = px4::WorkQueueFindOrCreate(px4::wq_configurations::test1);
	TEST_ASSERT(wq1 != nullptr, "WorkQueueFindOrCreate returns non-null for test1");

	// Find the same work queue again (should return same instance)
	px4::WorkQueue *wq1_again = px4::WorkQueueFindOrCreate(px4::wq_configurations::test1);
	TEST_ASSERT(wq1_again == wq1, "WorkQueueFindOrCreate returns same instance");

	// Create test work queue 2
	px4::WorkQueue *wq2 = px4::WorkQueueFindOrCreate(px4::wq_configurations::test2);
	TEST_ASSERT(wq2 != nullptr, "WorkQueueFindOrCreate returns non-null for test2");
	TEST_ASSERT(wq2 != wq1, "test2 is different from test1");

	// Print status
	px4::WorkQueueManagerStatus();

	// Request stop for all work queues
	if (wq1) wq1->request_stop();
	if (wq2) wq2->request_stop();

	// Give them time to stop
	vTaskDelay(pdMS_TO_TICKS(200));

	// Stop manager
	ret = px4::WorkQueueManagerStop();
	TEST_ASSERT(ret == 0, "WorkQueueManagerStop returns 0");

	vTaskDelay(pdMS_TO_TICKS(100));
}

/**
 * Test 3: Device bus to work queue mapping
 */
static void test_device_bus_mapping()
{
	debug_printf("Test 3: Device bus to work queue mapping\n");

	// Test SPI bus mapping
	const px4::wq_config_t &spi2_wq = px4::device_bus_to_wq(2, 2); // SPI bus 2
	TEST_ASSERT(strcmp(spi2_wq.name, "wq:SPI2") == 0, "SPI bus 2 maps to wq:SPI2");

	const px4::wq_config_t &spi3_wq = px4::device_bus_to_wq(2, 3); // SPI bus 3
	TEST_ASSERT(strcmp(spi3_wq.name, "wq:SPI3") == 0, "SPI bus 3 maps to wq:SPI3");

	// Test I2C bus mapping
	const px4::wq_config_t &i2c1_wq = px4::device_bus_to_wq(1, 1); // I2C bus 1
	TEST_ASSERT(strcmp(i2c1_wq.name, "wq:I2C1") == 0, "I2C bus 1 maps to wq:I2C1");

	// Test unknown bus (should return hp_default)
	const px4::wq_config_t &unknown_wq = px4::device_bus_to_wq(99, 99);
	TEST_ASSERT(strcmp(unknown_wq.name, "wq:hp_default") == 0, "Unknown bus maps to hp_default");
}

/**
 * Main test function
 */
extern "C" void test_work_queue_manager()
{
	debug_printf("\n========================================\n");
	debug_printf("  WorkQueueManager Tests\n");
	debug_printf("========================================\n");

	test_passed = 0;
	test_failed = 0;

	test_start_stop_manager();
	test_create_work_queues();
	test_device_bus_mapping();

	debug_printf("========================================\n");
	debug_printf("  Test Summary\n");
	debug_printf("========================================\n");
	debug_printf("Total tests: %d\n", test_passed + test_failed);
	debug_printf("Passed: %d\n", test_passed);
	debug_printf("Failed: %d\n", test_failed);

	if (test_failed == 0) {
		debug_printf("\n✅ All WorkQueueManager tests PASSED!\n");
	} else {
		debug_printf("\n❌ Some WorkQueueManager tests FAILED!\n");
	}
	debug_printf("========================================\n\n");
}

